const { Sequelize } = require('sequelize');
const config = require('config');

// 添加调试信息
console.log('Database config:', {
  hasConfig: !!config,
  hasData: !!config.data,
  configKeys: config ? Object.keys(config) : 'no config'
});

// 兼容不同的配置文件结构
let dbConfig;
if (config.data) {
  // 如果有 data 属性
  dbConfig = config.data;
} else if (config.mysql) {
  // 如果直接是 mysql 配置
  dbConfig = config.mysql;
} else {
  // 直接使用 config
  dbConfig = config;
}

console.log('Using database config:', {
  database: dbConfig.database,
  host: dbConfig.host,
  port: dbConfig.port,
  dialect: dbConfig.dialect
});

const sequelize = new Sequelize(
  dbConfig.database, 
  dbConfig.username, 
  dbConfig.password, 
  {
    host: dbConfig.host,
    port: dbConfig.port,
    dialect: dbConfig.dialect,
    logging: false // 关闭 SQL 日志，根据需要调整
  }
);

async function initializeDatabase() {
  try {
    await sequelize.authenticate();
    console.log('Database connection has been established successfully.');
    await sequelize.sync();
    console.log('All models were synchronized successfully.');
  } catch (error) {
    console.error('Unable to connect to the database:', error);
    throw error;
  }
}

module.exports = {
  sequelize,
  initializeDatabase
};